package com.lwl.leetcode;

/**
 * @author lwl
 * @Description 给定一个长度为 n 的整数数组 height 。有 n 条垂线，第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
 * <p>
 * 找出其中的两条线，使得它们与 x 轴共同构成的容器可以容纳最多的水。
 * <p>
 * 返回容器可以储存的最大水量。
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：<a href="https://leetcode.cn/problems/container-with-most-water">...</a>
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * @date 2023/7/26 0:45
 */
public class Code11MaxArea {

    public static void main(String[] args) {
        int[] height = {1, 8, 6, 2, 5, 4, 8, 3, 7};
        System.out.println(maxArea(height));
        System.out.println(maxArea2(height));
    }

    static public int maxArea(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int res = 0;
        while (left < right) {
            res = Math.max(res, (right - left) * Math.min(height[left], height[right]));
            if (height[left] >= height[right]) {
                right--;
            } else {
                left++;
            }
        }
        return res;
    }

    static public int maxArea2(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }
        int leftIndex = 0;
        int rightIndex = height.length - 1;
        int res = Integer.MIN_VALUE;
        while (leftIndex < rightIndex) {
            int curArea = (rightIndex - leftIndex) * Math.min(height[leftIndex], height[rightIndex]);
            res = Math.max(res, curArea);
            if (height[leftIndex] > height[rightIndex]) {
                rightIndex--;
            } else {
                leftIndex++;
            }
        }
        return res;
    }

//    static public int maxArea(int[] height) {
//        if (height == null || height.length == 0) {
//            return 0;
//        }
//        LinkedList<Integer> stack = new LinkedList<>();
//        int res = 0;
//        for (int i = 0; i < height.length; i++) {
//            while (!stack.isEmpty() && height[stack.peekLast()] <= height[i]) {
//                if (height[stack.peek()] == height[i] || stack.size() == 1) {
//                    stack.pollLast();
//                    continue;
//                }
//                int curHeight = height[stack.pollLast()];
//                int leftIndex = stack.isEmpty() ? -1 : stack.peekLast();
//                int rightIndex = i - 1;
//                int h = Math.min(height[stack.peekLast()], height[i]) - height[curHeight];
//                res += (rightIndex - leftIndex + 1) * h;
//            }
//            stack.addLast(i);
//        }
//        return res;
//    }

}
